package com.geek.project.geekverificationcodestarter.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;


/**
 * base64工具
 *
 * @author    geek
 */
@Slf4j
public class FileToBase64 {
	    
   
    /**
     * 把base64转化为文件.
     *
     * @param base64   base64
     * @param filePath 目标文件路径
     * @return boolean isTrue
     */
    public static Boolean decryptByBase64(String base64, String filePath) {
        if (StrUtil.isEmpty(base64) && StrUtil.isEmpty(filePath)) {
            return Boolean.FALSE;
        }
        try {
        	Files.write(Paths.get(filePath),
        			Base64.getDecoder().decode(base64.substring(base64.indexOf(',') + 1)), StandardOpenOption.CREATE);
        } catch (IOException e) {
            log.error("",e);
        }
        return Boolean.TRUE;
    }

    /**
     * 把文件转化为base64.
     *
     * @param filePath 源文件路径
     * @return String  转化后的base64
     */
    public static String encryptToBase64(String filePath) {
        if (!StrUtil.isEmpty(filePath)) {
            try {
            	byte[] bytes = Files.readAllBytes(Paths.get(filePath));
                return Base64.getEncoder().encodeToString(bytes);
            } catch (IOException e) {
            	log.error("",e);
            }
        }
        return null;
    }

    public static String getImage(BufferedImage image) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }

}